Node.js createServer
//appp.js
const http = require("http"); //載入node.js 模組
http
.createServer(function (request, response) {
if (request.url == "/") {
//if網址輸入127.0.0.1:9527
response.writeHead(200, { "Content-Type": "text/plain" }); //回傳給user的文字格式
response.write("Hi, World!");
response.end(); //回應中止
} else if (request.url == "/test") {
//if網址輸入127.0.0.1:9527/test
response.writeHead(200, { "Content-Type": "text/html" });
response.write("<h2>New page!</h2>");
response.end();
} else {
response.writeHead(200, { "Content-Type": "text/html" });
response.write("<h2>No Pages here.</h2>");
response.end();
}
})
.listen(9527);
.listen(9527)也可寫成server.listen(9527) //執行node appp.js後 在瀏覽器網址列打127.0.0.1:9527 即可回傳write中的內容 (127.0.0.1為本地主機,9527為port,注意有些port有固定用途)
//也可將plain改成html後於write中補上html tag 範例如下
response.writeHead(200, { "Content-Type": "text/html" });
response.write("<html><body>Hi, World!</body></html>");
載入 const path = require('path'); 可用以下語法
- 抓目錄路徑: path.dirname('/aa/bb/cc.js') 回傳 /aa/bb
- 抓檔名: path.basename('/aa/bb/cc.js') 回傳 cc.js
- 抓副檔名: path.extname('/aa/bb/cc.js') 回傳 js
- 分析路徑: path.parse('/aa/bb/cc.js') 回傳 上述所有物件
- 路徑合併:path.join(__dirname,'/aa') 回傳 前後路徑合併
ex:
const pathTest = path.join("C", "Users", "Administrator", "..", "Users"); console.log(pathTest); //C\Users\Users (註: ".."是往前退一層)